# !/usr/bin python3
# encoding: utf-8 -*-
import os
import shutil
import threading
import time
from datetime import datetime, timedelta
from typing import List

import pytest

import get_project_path
from common.driver import GlobalDriver, InitDriver
from common.file_load import load_yaml_file, write_yaml
from common.logger import GetLogger
from get_project_path import *


#
# import allure
# import pytest
# from PIL import Image
#
# from common.driver import GlobalDriver, InitDriver
# from common.file_load import load_yaml_file, write_yaml
# from common.logger import GetLogger
# from get_project_path import project_path


def pytest_collection_modifyitems(
        session: "Session", config: "Config", items: List["Item"]
) -> None:
    # item表示每个测试用例，解决用例名称中文显示问题
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode-escape")
        item._nodeid = item._nodeid.encode("utf-8").decode("unicode-escape")
@pytest.fixture(scope='session',autouse=True)
def generate_now_time() -> str:
    now = datetime.now()
    formatted_time = now.strftime('%Y%m%d%H%M%S')
    return formatted_time

@pytest.fixture(scope='session',autouse=True)
def generate_name(generate_now_time) -> str:
    group_name = f"新增模板组{generate_now_time}"
    template_name = f"新增模板{generate_now_time}"
    template_info = [group_name,template_name]
    return template_info

@pytest.fixture(scope='session',autouse=True)
def init_driver(get_common_info):
    url = get_common_info["CrmHost"]
    GlobalDriver.globalDriver = InitDriver()
    GlobalDriver.globalDriver.get(url)
    current_time = datetime.now()
    expiry_time = current_time + timedelta(hours=24)
    # 将时间转换为时间戳
    expiry_timestamp = int(expiry_time.timestamp())
    # document.cookie
    cookies = [{'domain': 'ab-crm-web-admin.test.nuanwa-tech.net', 'expiry': expiry_timestamp, 'httpOnly': False,
                'name': 'access_token', 'path': '/', 'sameSite': 'Lax', 'secure': False, 'value': get_common_info["cookie_value"]}]
    for cookie in cookies:
      GlobalDriver.globalDriver.add_cookie(cookie)
    GlobalDriver.globalDriver.get(url)
    GlobalDriver.globalDriver.set_window_size()
    yield
    # time.sleep(2)
    # GlobalDriver.globalDriver.quit()

@pytest.fixture(scope='session',autouse=True)
def aaget_logger():
    GetLogger.get_logger()
    GetLogger.logger.info('日志对象初始化成功')

@pytest.fixture(scope='session',autouse=True)
def clear_screenshot():
    # 删除screenshot目录下的所有文件
    screenshot_dir =  f"{get_project_path.project_path}\screenshot"
    if os.path.exists(screenshot_dir):
        shutil.rmtree(screenshot_dir)
        os.mkdir(screenshot_dir)
@pytest.fixture(scope='session',autouse=True)
def get_common_info():
    common_info = load_yaml_file('/config/common.yaml')
    return common_info
#
#
# pytest有一个自带的钩子函数，可以统计执行结果
def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """统计测试结果"""
    passed = len(terminalreporter.stats.get('passed', []))
    failed = len(terminalreporter.stats.get('failed', []))
    error = len(terminalreporter.stats.get('error', []))
    skipped = len(terminalreporter.stats.get('skipped', []))
    total = passed+failed+error+skipped
    # terminalreporter._sessionstarttime 会话开始时间
    duration = time.time() - terminalreporter._sessionstarttime
    print('total times:', duration, 'seconds')
    write_yaml('/result.yml',{"total":total,"passed":passed,"failed":failed,"skipped":skipped,"error":error})


if __name__ == '__main__':
    # gw0、gw1、gw2....gw10
    worker_id = 'gw100'
    print(int(worker_id[2:]))
    s = 'gw0_190.png'
    print(s.split('_')[1][:-4])